package com.sakura.hk.sakura.springboot.plugin.task;

import com.sakura.hk.sakura.springboot.plugin.SakuraBootType;
import com.sakura.hk.sakura.springboot.plugin.SakuraExtension;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.internal.AbstractTask;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.IOException;

/**
 * 生成新的Build Jar 文件
 *
 * @Author: 贺坤
 * @Date: 2021/7/13 16:22
 */
public class GenerateNewBuild extends DefaultTask {
    /**
     * 当前任务名称
     */
    public static final String MY_TASK_NAME = "generateNewBuild";
    /**
     * 构建jar名称
     */
    private String buildJarName;
    /**
     * 构建目录
     */
    private File buildDir;
    /**
     * 后缀
     */
    private String suffix;
    /**
     * 缓存文件路径
     */
    private String cacheFilePath;
    /**
     * 打包类型
     */
    private SakuraBootType type ;
    @TaskAction
    public void action() {
        init();
        // 执行控制行命令
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(getCommandString(), null, buildDir);
            // 让线程等待,防止过早进入下一步,删除文件
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static AbstractTask foundMyTask(Project project) {
        GenerateNewBuild task = project.getTasks().create(MY_TASK_NAME, GenerateNewBuild.class);
        task.dependsOn(SetSpringbootStartupMainClass.MY_TASK_NAME);
        task.setDescription("生成新的BuildJar包");
        return task;
    }

    /**
     * 得到控制行命令
     *
     * @return
     */
    private String getCommandString() {
        StringBuilder command = new StringBuilder();
        command.append("jar ");
        command.append("-cf0M ");
        command.append(buildJarName);
        command.append(suffix != null ? ("-" + suffix) : "");
        command.append(".");
        command.append(type.getValue());
        command.append(" ");
        command.append("-C ");
        command.append(cacheFilePath);
        command.append(" .");
        return command.toString();
    }

    private void init() {
        SakuraExtension sakuraExtension = getProject().getExtensions().getByType(SakuraExtension.class);
        this.buildJarName = sakuraExtension.getBuildJarName();
        this.suffix = sakuraExtension.getSuffix();
        this.buildDir = sakuraExtension.getBuildDir();
        // 检查缓存目录是否存在
        this.cacheFilePath = new File(sakuraExtension.getCacheDir(), sakuraExtension.getCacheName()).getAbsolutePath();
        this.type = sakuraExtension.getType();

    }
}
